package share

import (
	global "developer_tools/globals"
	"developer_tools/internal"
	"fmt"
	"os"
	"path/filepath"
)

var log_ = global.Logger

type ShareContent struct {
	// 将内容暂存到临时目录下的文件
	tmpDir string
	// 文件路径
	shareFilePath string
}

// NewShareContent creates a new ShareContent instance.
func NewShareContent() *ShareContent {
	return &ShareContent{}
}

// cat file | ssh localcode.share
/*
$ cat main.go | ssh localcode.share

// or

$ ssh localcode.share < main.go

$ ssh localcode.share tunnel=true < main.go
*/

func (s *ShareContent) CreateTmpFile(content []byte) bool {
	// 创建临时目录
	tmpDir, err := os.MkdirTemp("", "share")
	if err != nil {
		log_.Errorf("Failed to create temporary directory: %v", err)
		return false
	}

	s.tmpDir = tmpDir

	file := filepath.Join(tmpDir, "share_content.txt")
	if err := os.WriteFile(file, content, 0644); err != nil {
		log_.Errorf("Failed to create temporary file: %v", err)
		return false
	}
	s.shareFilePath = file

	log_.Debugf("Created temporary file: %s", file)

	return true
}

func (s *ShareContent) DoLocalCodeShare() string {
	defer os.RemoveAll(s.tmpDir)

	switch global.CurrentOS {
	case "windows":
		_cmd := fmt.Sprintf("cat %s -Encoding utf8 | ssh localcode.share", s.shareFilePath)
		log_.Debugf("Command on windows: %s", _cmd)
		out, err := internal.DoWindowsCmdExec(_cmd)
		if err != nil {
			return fmt.Sprintf("%s: %s", global.ExecuteCommandFailed, err)
		}
		return out
	case "linux", "darwin":
		_cmd := fmt.Sprintf("cat %s | ssh localcode.share", s.shareFilePath)
		log_.Debugf("Command on linux/unix: %s", _cmd)
		out, err := internal.DoUnixCmdExec(_cmd)
		if err != nil {
			return fmt.Sprintf("%s: %s", global.ExecuteCommandFailed, err)
		}
		return out
	default:
		return fmt.Sprintf("%s: %s", global.UnsupportedOS, global.CurrentOS)
	}
}
